import pygame
import Config
import re
import os
import os.path
import G

sep = os.sep
if sep == '\\':
   sep += sep

pathre = re.compile(r'^.*%(sep)s([^%(sep)s]*)' % {'sep': sep})

fontdict = dict()

def font(name=Config.default_font, size=Config.default_font_size, 
         bold=False, italic=False):
   if (name, size, bold, italic) in fontdict.keys():
      return fontdict[(name, size, bold, italic)]
   path = pygame.font.match_font(name, bold, italic)
   #filename = pathre.match(path).group(1)
   #path_real = os.path.abspath(os.curdir + os.sep + 'fonts' + os.sep + filename)
   f = pygame.font.Font(path, size)
   fontdict[(name, size, bold, italic)] = f
   return f

def message(text, pos, duration, textfont=None, color=(255,255,255), 
            centerx=False, centery = False):
   if textfont is None:
      textfont = font()
   mes = textfont.render(text, 1, color)
   pos_real = [pos[0], pos[1]]
   size = textfont.size(text)
   if centerx:
      pos_real[0] = Config.width/2 - size[0]/2
   if centery:
      pos_real[1] = Config.height/2 - size[1]/2
   G.messages.append([mes, pos_real, duration])

def render_lines(font, lines, *args):
   imagelines = list()
   maxwidth = 0
   height = 0
   for line in lines:
      imagelines.append(font.render(line, *args))
      w, h = imagelines[-1].get_rect().size
      height += h
      if w > maxwidth:
         maxwidth = w
   image = pygame.Surface((maxwidth, height))
   y = 0
   for l in imagelines:
      image.blit(l, (0, y))
      y += l.get_rect().height
   return image
